package com.caohx.bms.controller;

import com.caohx.bms.pojo.Book;
import com.caohx.bms.pojo.dto.BookDto;
import com.caohx.bms.pojo.dto.BookResponseDto;
import com.caohx.bms.pojo.ResponseMessage;
import com.caohx.bms.service.BookCategoryService;
import com.caohx.bms.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private  BookCategoryService categoryService;

    // 添加图书
    @PostMapping
    public ResponseMessage<Book> add(@Validated @RequestBody BookDto bookDto) {
        Book book = bookService.add(bookDto.trans2Book(categoryService), bookDto.getCategoryid());
        return ResponseMessage.success(book);
    }

    // 修改图书
    @PutMapping
    public ResponseMessage<Book> edit(@Validated @RequestBody BookDto bookDto) {
        Book updatedBook = bookService.edit(bookDto.trans2Book(categoryService),bookDto.getCategoryid());
        return ResponseMessage.success(updatedBook);
    }

    // 删除图书
    @DeleteMapping("/{bookId}")
    public ResponseMessage<Void> delete(@PathVariable Long bookId) {
        bookService.delete(bookId);
        return ResponseMessage.success(null);
    }

    // 查询指定ID的图书
    @GetMapping("/detail/{bookId}")
    public ResponseMessage<Book> get(@PathVariable Long bookId) {
        Book book = bookService.get(bookId);
        return ResponseMessage.success(book);
    }

    // 分页查询所有图书
    @GetMapping("/list")
    public ResponseMessage<Page<Book>> listBooks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Book> bookPage = bookService.listBooks(pageable);
        return ResponseMessage.success(bookPage);
    }
}
